package com.xiaobai.fileupload;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xiaobai.fileupload.dto.FileQuery;
import com.xiaobai.fileupload.dto.Result;
import com.xiaobai.fileupload.entity.ChunkEntity;
import com.xiaobai.fileupload.entity.FileListEntity;
import com.xiaobai.fileupload.result.UploadResult;
import com.xiaobai.fileupload.service.FileService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@Slf4j
@RequestMapping("file")
@RestController
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 上传文件块
     * vue-simple-uploader会调用post方法上传
     */
    @ApiOperation(value = "上传文件块")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result<?> uploadChunk(ChunkEntity chunkEntity) {
        log.info("文件名: {}, chunkNumber: {}", chunkEntity.getFilename(), chunkEntity.getChunkNumber());
        boolean flag = fileService.uploadChunk(chunkEntity);
        if (flag) {
            return Result.ok();
        }
        return Result.error();
    }

    /**
     * 检查文件块
     * vue-simple-uploader会调用get方法验证
     */
    @ApiOperation(value = "检查文件块")
    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public Result<?> checkChunk(ChunkEntity chunkEntity) {
        UploadResult result = fileService.checkChunk(chunkEntity);
        try {
            return Result.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ok(result);
        }
    }

    /**
     * 合并文件
     */
    @ApiOperation(value = "合并文件")
    @RequestMapping(value = "/merge", method = RequestMethod.POST)
    public Result<?> merge(@RequestBody FileListEntity fileInfo) {
        boolean flag = fileService.merge(fileInfo);
        if (flag) {
            return Result.ok();
        }
        return Result.error();
    }

    /**
     * 查询列表
     */
    @ApiOperation(value = "查询列表")
    @RequestMapping(value = "/selectFileList", method = RequestMethod.POST)
    public Result<?> selectFileList(@RequestBody FileQuery fileQuery) {
        IPage<FileListEntity> ipage = fileService.selectFileList(fileQuery);
        return Result.ok(ipage);
    }

}
